﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Gcssloop.Widget;
using Java.Util;
using mb;
using mb.Droid;

namespace libmp
{
    public static class MeView
    {
        public static LinearLayout layoutHeaderBottom;
        static ILog logger = ServiceLocator.Instance.Get<ILog>();
        static MyRecyclerAdapter adapter;
        static LinearLayout layout;
        static LinearLayout layoutHeader;
        static MyFragment myFragment;

        public static MyFragment CreateFragment()
        {
            myFragment = new MyFragment()
            {
                Title = "我的",
                    MyOnCreateView = (f, container) => CreateView(f),
                    MyOnPause = (f) => { logger.Log("meview pause"); },
                    MyOnResume = (f) => { logger.Log("meview resume"); },
                    MyOnVisibleHint = (f, b) =>
                    {
                        logger.Log("meview onvisible", b);
                        ReloadData();
                    }
            };

            User.me.OnChanged += delegate { ReloadData(); };
            return myFragment;
        }

        static void ReloadData()
        {
            if (myFragment == null || myFragment.View == null) return;
            resetUserInfo();
        }

        public static View CreateView(MyFragment f)
        {
            var ctx = StartActivity.This;
            layout = new LinearLayout(ctx);
            layout.Orientation = Orientation.Vertical;
            layout.SetBackgroundColor(Color.Rgb(238, 238, 238));

            layout.AddView(CreateHeader(f));
            layout.AddView(CreateBalance());
            layout.AddView(CreateRecharge());
            layout.AddView(CreateOperation());

            resetUserInfo();
            return layout;
        }

        //注册、登录、会员信息
        static View CreateHeader(MyFragment f)
        {
            //顶部布局分上下两个子布局
            var ctx = StartActivity.This;
            layoutHeader = new LinearLayout(ctx);
            layoutHeader.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 460);
            layoutHeader.SetBackgroundColor(Color.Rgb(251, 114, 153));
            layoutHeader.Orientation = Orientation.Vertical;
            layoutHeader.SetGravity(GravityFlags.Center);
            layoutHeader.SetGravity(GravityFlags.Top);

            //顶部二
            layoutHeaderBottom = new LinearLayout(ctx);
            layoutHeaderBottom.Orientation = Orientation.Horizontal;
            layoutHeaderBottom.LayoutParameters = new LinearLayout.LayoutParams(-1, -1);
            layoutHeaderBottom.SetGravity(GravityFlags.Center);
            layoutHeader.AddView(layoutHeaderBottom);

            return layoutHeader;
        }

        public static void RegisterAndLogIn(LinearLayout layoutHeaderBottom)
        {
            var ctx = StartActivity.This;
            var layoutRegister = new LinearLayout(ctx);
            layoutRegister.SetGravity(GravityFlags.Center);
            var layoutRegisterParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            layoutRegister.LayoutParameters = layoutRegisterParams;
            var btnRegister = new ImageView(ctx);
            btnRegister.SetImageDrawable(Util.DrawableFromFile("user/Register.png"));
            var btnRegisterParams = new LinearLayout.LayoutParams(-1, 180);
            btnRegisterParams.LeftMargin = 50;
            btnRegisterParams.RightMargin = 15;
            btnRegister.LayoutParameters = btnRegisterParams;
            layoutRegister.AddView(btnRegister);
            layoutHeaderBottom.AddView(layoutRegister);
            btnRegister.Click += (s, e) =>
            {
                logger.Log("注册了1");
                Register();
            };

            var layoutLogin = new LinearLayout(ctx);
            layoutLogin.SetGravity(GravityFlags.Center);
            var layoutLoginParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            layoutLogin.LayoutParameters = layoutLoginParams;
            var btnLogin = new ImageView(ctx);
            btnLogin.SetImageDrawable(Util.DrawableFromFile("user/Signin.png"));
            var btnLoginParams = new LinearLayout.LayoutParams(-1, 180);
            btnLoginParams.RightMargin = 50;
            btnLoginParams.LeftMargin = 15;
            btnLogin.LayoutParameters = btnLoginParams;
            layoutLogin.AddView(btnLogin);
            layoutHeaderBottom.AddView(layoutLogin);
            btnLogin.Click += (s, e) =>
            {
                logger.Log("登录了");
                LogIn();
            };
        }

        public static void CreateMyInfo(LinearLayout layoutHeaderBottom)
        {

            var ctx = StartActivity.This;
            var myInfoLeft = new LinearLayout(ctx);
            var myInfoLeftParams = new LinearLayout.LayoutParams(150, 150);
            myInfoLeftParams.LeftMargin = 40;
            myInfoLeft.LayoutParameters = myInfoLeftParams;
            myInfoLeft.AddView(Util.MakeImageView("avatar.png", true), new LinearLayout.LayoutParams(150, 150, 2));
            layoutHeaderBottom.AddView(myInfoLeft);

            myInfoLeft.Click += (s, e) =>
            {

                Util.PopMgr.ShowConfirm("你确定要退出登录吗？", b =>
                {
                    if (b)
                        libmp.User.me.Logout();
                });
            };

            var myInfoRight = new LinearLayout(ctx);
            myInfoRight.SetVerticalGravity(GravityFlags.CenterVertical);
            var myInfoRightParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            myInfoRightParams.LeftMargin = 40;
            myInfoRight.LayoutParameters = myInfoRightParams;
            // myInfoRight.SetBackgroundColor(Color.Blue);
            myInfoRight.Orientation = Orientation.Vertical;
            var myInfoRightTop = new LinearLayout(ctx);
            myInfoRightTop.Orientation = Orientation.Horizontal;
            var nikeNameText = new TextView(ctx);
            nikeNameText.Text = User.me.name;
            nikeNameText.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            nikeNameText.SetTextSize(ComplexUnitType.Pt, 10);
            nikeNameText.SetTextColor(Color.WhiteSmoke);
            myInfoRightTop.AddView(nikeNameText);
            myInfoRight.AddView(myInfoRightTop);
            layoutHeaderBottom.AddView(myInfoRight);
        }

        //页面余额，观看次数
        static View CreateBalance()
        {
            var ctx = StartActivity.This;
            var layoutBalance = new LinearLayout(ctx);
            layoutBalance.Orientation = Orientation.Horizontal;
            var layoutBalanceParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 200);
            layoutBalanceParams.SetMargins(20, -100, 20, 0);
            layoutBalance.LayoutParameters = layoutBalanceParams;
            layoutBalance.SetGravity(GravityFlags.Center);

            RCRelativeLayout layoutBalanceRCLayout = new RCRelativeLayout(ctx);
            var layoutBalanceRCLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 200);
            layoutBalanceRCLayout.LayoutParameters = layoutBalanceRCLayoutParams;
            layoutBalanceRCLayout.SetRadius(20);

            LinearLayout informationlayout = new LinearLayout(ctx);
            var informationlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
            informationlayout.LayoutParameters = informationlayoutParams;
            informationlayout.SetBackgroundColor(Color.Rgb(254, 254, 254));
            layoutBalanceRCLayout.AddView(informationlayout);

            layoutBalance.AddView(layoutBalanceRCLayout);

            BalanceInfo(informationlayout);
            return layoutBalance;
        }

        static void BalanceInfo(LinearLayout informationlayout)
        {
            var ctx = StartActivity.This;
            var layoutBalanceLeft = new LinearLayout(ctx);
            layoutBalanceLeft.Orientation = Orientation.Vertical;
            var layoutBalanceLeftParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1.0f);
            layoutBalanceLeft.LayoutParameters = layoutBalanceLeftParams;

            BalanceLeftInfo(layoutBalanceLeft);
            informationlayout.AddView(layoutBalanceLeft);

            var layoutBalanceCenter = new LinearLayout(ctx);
            var layoutBalanceCenterParams = new LinearLayout.LayoutParams(1, 110);
            layoutBalanceCenterParams.TopMargin = 45;
            layoutBalanceCenter.LayoutParameters = layoutBalanceCenterParams;
            layoutBalanceCenter.SetBackgroundColor(Color.Rgb(204, 204, 204));
            informationlayout.AddView(layoutBalanceCenter);

            var layoutBalanceRight = new LinearLayout(ctx);
            layoutBalanceRight.Orientation = Orientation.Vertical;
            var layoutBalanceRightParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1.0f);
            layoutBalanceRight.LayoutParameters = layoutBalanceRightParams;
            BalanceRightInfo(layoutBalanceRight);
            informationlayout.AddView(layoutBalanceRight);

        }

        static TextView ViewsNumsValue;
        static TextView balanceValue;
        static void BalanceLeftInfo(LinearLayout layoutBalanceLeft)
        {
            var ctx = StartActivity.This;

            var layoutBalanceLeftBottom = new LinearLayout(ctx);
            layoutBalanceLeftBottom.SetHorizontalGravity(GravityFlags.CenterHorizontal);
            var layoutBalanceLeftBottomParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 50);
            layoutBalanceLeftBottomParams.TopMargin = 30;
            layoutBalanceLeftBottom.LayoutParameters = layoutBalanceLeftBottomParams;
            ViewsNumsValue = new TextView(ctx);
            layoutBalanceLeftBottom.AddView(ViewsNumsValue);
            layoutBalanceLeft.AddView(layoutBalanceLeftBottom);

            var layoutBalanceLeftTop = new LinearLayout(ctx);
            layoutBalanceLeftTop.SetHorizontalGravity(GravityFlags.CenterHorizontal);
            var layoutBalanceLeftTopParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 50);
            layoutBalanceLeftTopParams.TopMargin = 30;
            layoutBalanceLeftTop.LayoutParameters = layoutBalanceLeftTopParams;

            var ViewsNums = new TextView(ctx);
            ViewsNums.Text = "剩余观看集数";
            ViewsNums.SetTextColor(Color.Rgb(204, 204, 204));
            layoutBalanceLeftTop.AddView(ViewsNums);
            layoutBalanceLeft.AddView(layoutBalanceLeftTop);

        }

        static void BalanceRightInfo(LinearLayout layoutBalanceRight)
        {
            var ctx = StartActivity.This;

            var layoutBalanceRightBottom = new LinearLayout(ctx);
            layoutBalanceRightBottom.SetHorizontalGravity(GravityFlags.CenterHorizontal);
            layoutBalanceRightBottom.Orientation = Orientation.Horizontal;
            var layoutBalanceRightBottomParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 50);
            layoutBalanceRightBottomParams.TopMargin = 30;
            layoutBalanceRightBottom.LayoutParameters = layoutBalanceRightBottomParams;
            balanceValue = new TextView(ctx);
            if (User.me.balance > 0)
            {
                balanceValue.Text = User.me.balance + "";
                balanceValue.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            }
            else
            {
                balanceValue.Text = "—";
                balanceValue.SetTextColor(Color.Rgb(204, 204, 204));
            }
            layoutBalanceRightBottom.AddView(balanceValue);
            layoutBalanceRight.AddView(layoutBalanceRightBottom);

            var layoutBalanceRightTop = new LinearLayout(ctx);
            layoutBalanceRightTop.SetHorizontalGravity(GravityFlags.CenterHorizontal);
            var layoutBalanceRightTopParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 50);
            layoutBalanceRightTopParams.TopMargin = 30;
            layoutBalanceRightTop.LayoutParameters = layoutBalanceRightTopParams;
            var balance = new TextView(ctx);
            balance.Text = "可提现(元)";
            balance.SetTextColor(Color.Rgb(204, 204, 204));
            layoutBalanceRightTop.AddView(balance);
            layoutBalanceRight.AddView(layoutBalanceRightTop);

        }

        static void resetUserInfo()
        {
            if (!myFragment.IsAdded) return;

            layoutHeaderBottom.RemoveAllViews();
            if (User.me.token.Length > 0)
                CreateMyInfo(layoutHeaderBottom);
            else
                RegisterAndLogIn(layoutHeaderBottom);

            if (User.me.VideoCanPlayRemain > 0)
            {
                ViewsNumsValue.Text = User.me.VideoCanPlayRemain + "";
                ViewsNumsValue.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
                balanceValue.Text = User.me.balance + "";
                balanceValue.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            }
            else
            {
                ViewsNumsValue.Text = "—";
                ViewsNumsValue.SetTextColor(Color.Rgb(204, 204, 204));
                balanceValue.Text = "—";
                balanceValue.SetTextColor(Color.Rgb(204, 204, 204));
            }

            if (tvUserId != null)
                tvUserId.Text = User.me.id + "\n" + User.me.token;
        }

        static TextView tvUserId;
        static View CreateRecharge()
        {
            var ctx = StartActivity.This;
            var layoutRecharge = new LinearLayout(ctx);
            layoutRecharge.Orientation = Orientation.Horizontal;
            layoutRecharge.SetBackgroundColor(Color.Rgb(254, 254, 254));
            var layoutRechargeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 200);
            layoutRechargeParams.TopMargin = 40;
            layoutRecharge.LayoutParameters = layoutRechargeParams;

            tvUserId = new TextView(ctx).SetParent(layoutRecharge);

            return layoutRecharge;
        }

        //会员功能操作
        static View CreateOperation()
        {
            var ctx = StartActivity.This;
            var layoutOperation = new LinearLayout(ctx);
            layoutOperation.Orientation = Orientation.Vertical;
            layoutOperation.LayoutParameters = new LinearLayout.LayoutParams(-1, -2)
            {
                TopMargin = 30,
            };
            var btnInfoList = new String[4][]
            {
                new String[] { "user/Lishijilu.png", "历史记录" },
                new String[] { "user/Downloadcache.png", "离线缓存" },
                new String[] { "user/Membershipexpires.png", "会员到期日" },
                new String[] { "user/Passwordmodification.png", "密码修改" }
            };
            var btnActionList = new Action[]
            {
                HistoryRecord,
                OfflineCache,
                MemberCenter,
                () =>
                {
                    // DemandFrequencyView.CreateFragment().Show(myFragment.FragmentManager, "demandFrequency");
                    Util.PopMgr.ShowToast("密码修改暂不支持");
                }
            };
            foreach (var item in mb.ForEachHelper.WithIndex(btnInfoList))
            {
                layoutOperation.AddView(
                    Util.MakeFlatIconTextButton(item.Value[0], item.Value[1])
                    .SetClickHandler(delegate { btnActionList[item.Index](); })
                );
            }
            return layoutOperation;
        }

        public static void Register()
        {
            var mfrag = RegisteredAccountView.CreateFragment();
            var ft = StartActivity.This.SupportFragmentManager.BeginTransaction();
            var id = StartActivity.This.ContentViewId;
            ft.Replace(id, mfrag);
            ft.AddToBackStack("register");
            ft.Commit();
        }

        public static void LogIn()
        {
            var frag = SignInView.CreateFragment(ok =>
            {
                logger.Log("login result", ok);
                if (ok)
                {

                }
            });

            var ft = StartActivity.This.SupportFragmentManager.BeginTransaction();
            var id = StartActivity.This.ContentViewId;
            ft.Replace(id, frag);
            ft.AddToBackStack("signin");
            ft.Commit();
        }

        public static void MemberCenter()
        {
            // var mfrag = MemberCenterView.CreateFragment();
            // var ft = StartActivity.This.SupportFragmentManager.BeginTransaction();
            // var id = StartActivity.This.ContentViewId;
            // ft.Replace(id, mfrag);
            // ft.AddToBackStack("memberCenter");
            // ft.Commit();

        }

        public static void OfflineCache()
        {
            var mfrag = new OfflineCacheView().CreateFragment();
            var ft = StartActivity.This.SupportFragmentManager.BeginTransaction();
            var id = StartActivity.This.ContentViewId;
            ft.Replace(id, mfrag);
            ft.AddToBackStack("OfflineCacheView");
            ft.Commit();
        }
        public static void HistoryRecord()
        {
            var mfrag = new HistoryRecordView().CreateFragment();
            var ft = StartActivity.This.SupportFragmentManager.BeginTransaction();
            var id = StartActivity.This.ContentViewId;
            ft.Replace(id, mfrag);
            ft.AddToBackStack("HistoryRecordView");
            ft.Commit();
        }
    };

}